package com.yuanduo_app.http;

import com.google.gson.Gson;
import com.yuanduo_app.consts.SpName;
import com.yuanduo_app.entity.UserInfoEntity;
import com.yuanduo_app.manager.CacheManager;
import com.xujl.fastlib.http.NetworkManager;
import com.xujl.fastlib.utils.SpHelper;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class DataSource {
    //            public class DataSource implements ApiService {
    public static DataSource getInstance () {
        return Holder.INSTANCE;
    }

    private DataSource () {
    }

    public static ApiService createApi () {
        return NetworkManager.getInstance().create(ApiService.class);
    }

    public static RequestBody createBody (Object params) {
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(params));
    }

    public static RequestBody createUploadPicBody (String path) {
        final MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        //注意，file是后台约定的参数，如果是多图，file[]，如果是单张图片，file就行zgxl
        File file = new File(path);
        //这里上传的是多图
        builder.addFormDataPart("uploadFile", file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
        return builder.build();
    }

    public void saveUserInfo (UserInfoEntity data) {
//        SpHelper.getInstance().edit().putObject(SpName.USER_INFO, data)
//                .putString(SpName.TOKEN, data.getToken())
//                .commit();
//        CacheManager.getInstance().setToken(data.getToken());
//        CacheManager.getInstance().setUserInfoEntity(data);
//        //网络请求设置统一header
//        NetworkManager.getInstance().setHeaders(RequestCommonParams.createHeaders());
    }

    public void exitLogin () {
        SpHelper.getInstance().edit()
                .putString(SpName.TOKEN, "")
                .putString(SpName.PWD, "")
                .commit();
        CacheManager.getInstance().init();
        //网络请求设置统一header
        NetworkManager.getInstance().setHeaders(RequestCommonParams.createHeaders());
    }


    private static class Holder {
        private static final DataSource INSTANCE = new DataSource();
    }

//<editor-fold desc="part1">

}
